package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cookie03.do")
public class Cookie03Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //修改Cookie 方法1
        Cookie[] cookies = request.getCookies();
        Cookie cookie01 = findByName(cookies, "cookie01");
        cookie01.setValue("Value11111");
        //负数：设置生命周期为session级别。。。
        cookie01.setMaxAge(-1);
        Cookie cookie02 = findByName(cookies, "cookie02");
        //0：立即删除该cookie
        cookie02.setMaxAge(0);
        Cookie cookie03 = findByName(cookies, "cookie03");
        //正数：单位：秒 变成有具体期限的cookie
        cookie03.setMaxAge(60 * 60);
        addCookies(request, response, cookie01, cookie02, cookie03);
    }

    public Cookie findByName(Cookie[] cookies, String name) {
        if (name == null) {
            return null;
        }
        for (int i = 0; i < cookies.length; i++) {
            if (name.equals(cookies[i].getName())) {
                return cookies[i];
            }
        }
        return null;
    }

    public void addCookies(HttpServletRequest request, HttpServletResponse response, Cookie... cookies) {
        for (int i = 0; i < cookies.length; i++) {
            response.addCookie(cookies[i]);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
